package com.yjzx.util.service.aop.duplicateSubmit;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author yjzx
 * @date 2024/06/04
 * @description 接口请求频率限制
 */
@Aspect
@Component
@Order(2)
public class DuplicateSubmitAspect {


    @Pointcut("execution(public * com..controller..*.*(..))")
    public void webLogger() {
    }

    @Before("webLogger() && @annotation(token)")
    public void before(final JoinPoint joinPoint, DuplicateSubmit token){
        if (token!=null){
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            String uri = request.getRequestURI();
            HttpSession session = request.getSession();
            Object oldTimeObject = session.getAttribute(uri);
            if(oldTimeObject ==null ){
                  session.setAttribute(uri,System.currentTimeMillis());
            }else {
                 Long oldTime = (Long)oldTimeObject;
                 if(System.currentTimeMillis() - oldTime > token.timeout()){
                     session.setAttribute(uri,System.currentTimeMillis());
                 }else {
                     throw new RuntimeException("您的操作太快了,慢点哦！");
                 }
            }

        }
    }


}